<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="村名字" >
        <el-input
          v-model="queryParams['bankVillage.villageName']"
          placeholder="请输入村名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="评议员名字" prop="reviewerName">
        <el-input
          v-model="queryParams.reviewerName"
          placeholder="请输入评议员名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="reviewerNumber">
        <el-input
          v-model="queryParams.reviewerNumber"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bank:senator:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bank:senator:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bank:senator:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bank:senator:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="senatorList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="评议员编号" align="center" prop="reviewerId" />
      <el-table-column label="村名字" align="center" prop="bankVillage.villageName" />
      <el-table-column label="评议员名字" align="center" prop="reviewerName" />
      <el-table-column label="身份证号" align="center">
        <template slot-scope="scope">
          {{ scope.row.reviewerNumber.substring(0, 6) + '********' + scope.row.reviewerNumber.substring(14) }}
        </template>
      </el-table-column>

      <el-table-column label="手机号" align="center" prop="reviewerPhonenumber" />
      <el-table-column label="居住地址" align="center" prop="reviewerAddress" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bank:senator:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bank:senator:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评议员管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="村名字" prop="villageId">
          <el-select v-model="form.villageId" placeholder="请选择村名字">
            <el-option
              v-for="item in villageList"
              :key="item.villageId"
              :label="item.villageName"
              :value="item.villageId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评议员名字" prop="reviewerName">
          <el-input v-model="form.reviewerName" placeholder="请输入评议员名字" />
        </el-form-item>
        <el-form-item label="身份证号" prop="reviewerNumber">
          <el-input v-model="form.reviewerNumber" placeholder="请输入身份证号" maxlength="18"/>
        </el-form-item>
        <el-form-item label="手机号" prop="reviewerPhonenumber">
          <el-input v-model="form.reviewerPhonenumber" placeholder="请输入手机号" maxlength="11"/>
        </el-form-item>
        <el-form-item label="居住地址" prop="reviewerAddress">
          <el-input v-model="form.reviewerAddress" placeholder="请输入居住地址" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSenator, getSenator, delSenator, addSenator, updateSenator } from "@/api/bank/senator";
import {listVillage} from "@/api/bank/village";
import { getUserProfile } from "@/api/system/user";
import {listReview} from "@/api/bank/review";

export default {
  name: "Senator",
  data() {
    return {
      //当前用户信息
      user: {},
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评议员管理表格数据
      senatorList: [],
      // 行政村数据
      villageList:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        reviewerVillageName: null,
        'bankVillage.villageName':null,
        reviewerName: null,
        reviewerNumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        villageId: [
          { required: true, message: "村名字不能为空", trigger: "blur" }
        ],
        reviewerName: [
          { required: true, message: "评议员名字不能为空", trigger: "blur" }
        ],
        reviewerNumber: [
          { required: true, message: "身份证号不能为空", trigger: "blur" },
          { min: 18, max: 18, message: "身份证号必须是18位", trigger: "blur" }
        ],
        reviewerPhonenumber: [
          { required: true, message: "手机号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "手机号必须是11位", trigger: "blur" }
        ],

      }
    };
  },
  created() {
    this.getUser();
  },
  methods: {

    /** 查询当前用户信息，并筛选行政村和评议员列表 */
    getUser() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.getVillageList();
      });
    },

    /** 查询行政村列表，并根据当前用户ID过滤 */
    getVillageList() {
      listVillage({pageSize:1000000}).then(response => {
        // 确认response.rows是一个数组且不为空
        if (Array.isArray(response.rows) && response.rows.length) {
          // 过滤出当前用户管理的行政村
          if (this.user.userId != 17 && this.user.userId != 1) {
            this.villageList = response.rows.filter(village => village.superVisorId == this.user.userId);
          } else {
            // 如果是特定ID，则不进行过滤，直接使用全部行政村数据
            this.villageList = response.rows;

          }
        } else {
          // 如果response.rows不是数组或者为空，可以在这里处理
          console.log("No village data received or not in expected format:", response.rows);
        }
        // 根据过滤后的行政村ID获取评议员信息
        this.getList();
      });
    },

    /** 查询评议员信息列表，并根据行政村过滤 */
    getList() {
      this.loading = true;
      listSenator(this.queryParams).then(response => {
        // 确认response.rows是一个数组且不为空
        if (Array.isArray(response.rows) && response.rows.length) {
          // 过滤出属于当前用户管理的行政村的评议员信息
          if(this.user.userId != 17 && this.user.userId != 1){
            this.senatorList = response.rows.filter(senator =>
              this.villageList.some(village => village.villageId == senator.villageId)
            );
          } else {
            // 如果用户ID为17，则不进行过滤，显示所有评议员
            this.senatorList = response.rows;
          }
          this.total = this.senatorList.length; // 更新总条数
        } else {
          // 如果response.rows不是数组或者为空，可以在这里处理
          console.log("No senator data received or not in expected format:", response.rows);
        }
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reviewerId: null,
        villageId: null,
        reviewerVillageName: null,
        reviewerName: null,
        reviewerNumber: null,
        reviewerPhonenumber: null,
        reviewerAddress: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reviewerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加评议员管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const reviewerId = row.reviewerId || this.ids
      getSenator(reviewerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改评议员管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.reviewerId != null) {
            updateSenator(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSenator(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reviewerIds = row.reviewerId ? [row.reviewerId] : this.ids; // 确保reviewerIds始终是数组形式
      // 获取所有评议表信息
      listReview({pageSize: 100000000}).then(reviewResponse => {
        const reviews = reviewResponse.rows || [];
        const deletableIds = [];
        const undeletableIds = [];

        reviewerIds.forEach(id => {
          // 检查是否存在评议信息
          const hasReview = reviews.some(review => review.reviewerId === id);
          if (hasReview) {
            // 如果存在评议信息，记录不可删除的评议员ID
            undeletableIds.push(id);
          } else {
            // 如果不存在评议信息，记录可删除的评议员ID
            deletableIds.push(id);
          }
        });

        // 如果有不可删除的评议员
        if (undeletableIds.length > 0) {
          if (undeletableIds.length === reviewerIds.length) {
            // 如果所有选中的评议员都不可删除，只显示一条错误信息
            this.$modal.msgError("选中的评议员均存在评议信息，无法删除");
          } else {
            // 如果部分评议员不可删除，显示具体的ID
            this.$modal.msgError(`评议员ID为"${undeletableIds.join(', ')}"存在评议信息，不允许删除`);
          }
        }

        // 如果有可删除的评议员
        if (deletableIds.length > 0) {
          this.$modal.confirm(`是否确认删除评议员管理编号为"${deletableIds.join(', ')}"的数据项？`).then(() => {
            // 直接传递数组到接口
            return delSenator(deletableIds);
          }).then(() => {
            this.getList();
            this.$modal.msgSuccess("删除成功");
          }).catch(() => {});
        }
      });
    },


    /** 导出按钮操作 */
    handleExport() {
      this.download('bank/senator/export', {
        ...this.queryParams
      }, `senator_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
